package controller;

import java.util.ArrayList;

import manager.BidMgr;
import entity.Bid;
import entity.Section;
import entity.Student;
import exception.MultipleValidationErrors;
import exception.ValidationError;

/**
 * @author Mohamed Safiullah, Sheryl Tay
 * 
 */
public class BidCtrl {

	private BidMgr bidMgr;
	private CourseCtrl courseCtrl;
	private StudentCtrl studentCtrl;
	private RoundCtrl roundCtrl;
	private SectionCtrl sectionCtrl;

	public BidCtrl() {
		bidMgr = new BidMgr();
	}

	public void addBid(Student student, Section section, double bidAmount) {

		bidMgr.addBid(new Bid(student, section, bidAmount));
	}

	public void deleteBid(Bid bid) throws MultipleValidationErrors {

		String userId = bid.getStudent().getUserId();
		String courseCode = bid.getSection().getCourse().getCourseCode();
		String sectionCode = bid.getSection().getSectionCode();

		ArrayList<String> errorMessages = new ArrayList<String>();

		if (!courseCtrl.hasCourse(courseCode)) {
			errorMessages.add("invalid course");
		}
		if (!studentCtrl.hasStudent(userId)) {
			errorMessages.add("invalid userid");
		}
		if (courseCtrl.hasCourse(courseCode)
				&& sectionCtrl.hasSectionForCourse(sectionCode, courseCode)) {
			errorMessages.add("invalid section");
		}
		if (!roundCtrl.getCurrentRound().isRoundOpen()) {
			errorMessages.add("round ended");
		}

		if (errorMessages.isEmpty()) {
			try {
				bidMgr.deleteBid(userId, courseCode, sectionCode);
			} catch (ValidationError e) {
				errorMessages.add(e.getMessage());
			}
		}

		if (!errorMessages.isEmpty()) {
			throw new MultipleValidationErrors(errorMessages);
		}

	}

	public void deleteAllBids() {
		bidMgr.deleteAllBids();
	}

	public ArrayList<Bid> retrieveBidsForStudent(Student student) {
		return bidMgr.retrieveBidsForStudent(student.getUserId());
	}

	public ArrayList<Bid> retrieveBidsForSections(Section section) {
		return bidMgr.retrieveBidsForSection(section.getCourse()
				.getCourseCode(), section.getSectionCode());
	}

}
